<template>
    <div class="compare-page">
        <!-- 顶部 Header -->
        <header class="compare-header">
            <el-button type="text" :icon="ArrowLeft" @click="goBack">返回</el-button>
            <div class="header-right">
                <span class="similarity">
                    文本相似度：
                    <b class="similarity-badge">{{ similarity }}%</b>
                </span>
                <!-- <div class="connection-controls">
                     <span class="connection-control-title">连线调整:</span>
                     <div class="connection-control-buttons">
                         <el-button size="small" @click="adjustConnectionOffset('left', -5)" title="左侧连接点向左移动">←L</el-button>
                         <el-button size="small" @click="adjustConnectionOffset('left', 5)" title="左侧连接点向右移动">L→</el-button>
                         <el-button size="small" @click="adjustConnectionOffset('right', -5)" title="右侧连接点向左移动">←R</el-button>
                         <el-button size="small" @click="adjustConnectionOffset('right', 5)" title="右侧连接点向右移动">R→</el-button>
                         <el-button size="small" type="info" @click="resetConnectionOffset()" title="重置连线位置">重置</el-button>
                     </div>
                 </div> -->
                <el-button type="primary" :icon="Reading" @click="showDiffPoint">差异点</el-button>
            </div>
        </header>

        <!-- 中部 PDF 对比区 + 差异列表 -->
        <div class="compare-main" :class="{ 'with-diff-list': showDiffList }">
            <div class="pdf-compare-content">
                <!-- 左侧PDF控制面板 -->
                <div class="pdf-container">
                    <div class="control-panel">
                        <div class="zoom-controls">
                            <el-button-group>
                                <el-button :icon="ZoomIn" @click="zoomIn(1)" size="small" title="放大"></el-button>
                                <el-button :icon="ZoomOut" @click="zoomOut(1)" size="small" title="缩小"></el-button>
                                <el-button :icon="Refresh" @click="resetZoom(1)" size="small" title="重置"></el-button>
                            </el-button-group>
                            <span class="zoom-level">{{ Math.round(zoomLevels.left * 100) }}%</span>
                        </div>
                        <div class="page-controls">
                            <el-button size="small" :icon="ArrowUp" @click="prevPage(1)" 
                                :disabled="page1 <= 1" title="上一页" circle />
                            <span class="page-display">{{ page1 }}/{{ pdf1TotalPages }}</span>
                            <el-button size="small" :icon="ArrowDown" @click="nextPage(1)" 
                                :disabled="page1 >= pdf1TotalPages" title="下一页" circle />
                        </div>
                    </div>
                    <div class="pdf-viewer" ref="leftPdfViewer">
                        <canvas ref="pdfCanvas" class="pdf-canvas pdf-canvas-full"></canvas>
                    </div>
                </div>

                <!-- 右侧PDF控制面板 -->
                <div class="pdf-container">
                    <div class="control-panel">
                        <div class="zoom-controls">
                            <el-button-group>
                                <el-button :icon="ZoomIn" @click="zoomIn(2)" size="small" title="放大"></el-button>
                                <el-button :icon="ZoomOut" @click="zoomOut(2)" size="small" title="缩小"></el-button>
                                <el-button :icon="Refresh" @click="resetZoom(2)" size="small" title="重置"></el-button>
                            </el-button-group>
                            <span class="zoom-level">{{ Math.round(zoomLevels.right * 100) }}%</span>
                        </div>
                        <div class="page-controls">
                            <el-button size="small" :icon="ArrowUp" @click="prevPage(2)" 
                                :disabled="page2 <= 1" title="上一页" circle />
                            <span class="page-display">{{ page2 }}/{{ pdf2TotalPages }}</span>
                            <el-button size="small" :icon="ArrowDown" @click="nextPage(2)" 
                                :disabled="page2 >= pdf2TotalPages" title="下一页" circle />
                        </div>
                    </div>
                    <div class="pdf-viewer" ref="rightPdfViewer">
                        <canvas ref="pdfCanvas2" class="pdf-canvas pdf-canvas-full"></canvas>
                    </div>
                </div>

                <!-- 差异列表 - 改为内嵌式布局 -->
                <div v-if="showDiffList" class="diff-list-sidebar">
                    <div class="diff-list-header">
                        <h3>差异列表</h3>
                        <el-button :icon="Close" @click="showDiffList = false" size="small" circle></el-button>
                    </div>
                    <div class="diff-list-content">
                        <div v-for="(item, idx) in diffList" :key="idx" class="diff-item diff-item-hover"
                            @click="highlightDiff(idx)">
                            <div class="diff-title">{{ item.type }}</div>
                            <div class="diff-row">
                                <span class="diff-label">左：</span>
                                <span class="text-red-500">{{ item.details.text.document1 }}</span>
                            </div>
                            <div class="diff-row">
                                <span class="diff-label">右：</span>
                                <span class="text-white">{{ item.details.text.document2 }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 底部 文件名和翻页 -->
        <footer class="compare-footer" :class="{ 'with-diff-list': showDiffList }">
            <div class="footer-block">
                <span class="footer-filename">{{ pdf1Name }}</span>
                <span class="footer-page">
                    <span class="page-current">{{ page1 }}</span>
                    <span class="page-sep">/</span>
                    <span class="page-total">{{ pdf1TotalPages }}</span>
                </span>
            </div>
            <div class="footer-block">
                <span class="footer-filename">{{ pdf2Name }}</span>
                <span class="footer-page">
                    <span class="page-current">{{ page2 }}</span>
                    <span class="page-sep">/</span>
                    <span class="page-total">{{ pdf2TotalPages }}</span>
                </span>
            </div>
        </footer>
    </div>
</template>

<script setup>

import { Reading, ArrowLeft, ArrowRight, ArrowUp, ArrowDown, ZoomIn, ZoomOut, Refresh, Close } from '@element-plus/icons-vue'
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import { ElLoading } from 'element-plus'
import * as pdfjsLib from 'pdfjs-dist/build/pdf.min.mjs'

pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
    'pdfjs-dist/build/pdf.worker.mjs',
    import.meta.url
).toString()


import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute();
console.log(`route.params.res`, route.params); // 0


const similarity = ref(87)
const pdf1Url = ref('')
const pdf2Url = ref('')
const pdf1Name = '原文稿'
const pdf2Name = '对比文稿'
const page1 = ref(1)
const page2 = ref(1)
const pdf1TotalPages = ref(1)
const pdf2TotalPages = ref(1)
const showDiffList = ref(false)

const pdfCanvas = ref(null)
const pdfCanvas2 = ref(null)
const leftPdfViewer = ref(null)
const rightPdfViewer = ref(null)

let pdf1Instance = null
let pdf2Instance = null
let pdf1RenderPromise = Promise.resolve();
let pdf2RenderPromise = Promise.resolve();

const diffList = ref([]) // 初始为空

// 缩放控制相关
const zoomLevels = ref({
    left: 2.0,
    right: 2.0
})
const defaultZoom = 2.0
const minZoom = 0.5
const maxZoom = 3.0
const zoomStep = 0.25
// 连线位置偏移量 - 设置初始值使连线准确连接到文字差异
// 左侧文档连接点在右边界，右侧文档连接点在左边界
const connectionOffset = ref({ left: 5, right: -5 })
const isRendering1 = ref(false) // 防止重复渲染的标志
const isRendering2 = ref(false) // 防止重复渲染的标志

let loading = null;

/**
 * 调整连线偏移量
 * @param {string} side 'left' 或 'right'
 * @param {number} value 偏移量增减值
 */
function adjustConnectionOffset(side, value) {
    if (side === 'left') {
        connectionOffset.value.left += value;
    } else {
        connectionOffset.value.right += value;
    }
    console.log(`当前连线偏移量: 左侧=${connectionOffset.value.left}, 右侧=${connectionOffset.value.right}`);
    
    // 重新绘制连线
    if (currentDiffIdx !== null) {
        highlightDiff(currentDiffIdx);
    }
}

/**
 * 重置连线偏移量到默认值
 */
function resetConnectionOffset() {
    // 根据屏幕宽度自动调整偏移量
    autoAdjustConnectionOffset();
    
    // 重新绘制连线
    if (currentDiffIdx !== null) {
        highlightDiff(currentDiffIdx);
    }
}

// 在翻页后自动高亮
watch([page1, page2], () => {
    // highlightDiffsForCurrentPage();
});

const showDiffPoint = () => {
    showDiffList.value = !showDiffList.value
}



// 修改loadAndRenderPdf，支持缩放和缓存pdf实例
async function loadAndRenderPdf(pageNum = 1, zoom = null) {
    if (!pdf1Instance || isRendering1.value) return;
    isRendering1.value = true;
    try {
        await pdf1RenderPromise;
        
        // 使用传入的zoom或当前zoomLevels.left
        const actualZoom = zoom !== null ? zoom : zoomLevels.value.left;
        
        const page = await pdf1Instance.getPage(pageNum);
        const dpr = window.devicePixelRatio || 1;
        const viewport = page.getViewport({ scale: actualZoom });
        const canvas = pdfCanvas.value;
        const context = canvas.getContext('2d');
        canvas.width = viewport.width * dpr;
        canvas.height = viewport.height * dpr;
        canvas.style.width = `${viewport.width}px`;
        canvas.style.height = `${viewport.height}px`;
        context.setTransform(dpr, 0, 0, dpr, 0, 0);
        pdf1RenderPromise = page.render({
            canvasContext: context,
            viewport: viewport
        }).promise;
        await pdf1RenderPromise;
    } finally {
        isRendering1.value = false;
    }
}

// 右侧PDF渲染，支持缩放和缓存pdf实例
async function loadAndRenderPdf2(pageNum = 1, zoom = null) {
    if (!pdf2Instance || isRendering2.value) return;
    isRendering2.value = true;
    try {
        await pdf2RenderPromise;
        
        // 使用传入的zoom或当前zoomLevels.right
        const actualZoom = zoom !== null ? zoom : zoomLevels.value.right;
        
        const page = await pdf2Instance.getPage(pageNum);
        const dpr = window.devicePixelRatio || 1;
        const viewport = page.getViewport({ scale: actualZoom });
        const canvas = pdfCanvas2.value;
        const context = canvas.getContext('2d');
        canvas.width = viewport.width * dpr;
        canvas.height = viewport.height * dpr;
        canvas.style.width = `${viewport.width}px`;
        canvas.style.height = `${viewport.height}px`;
        context.setTransform(dpr, 0, 0, dpr, 0, 0);
        pdf2RenderPromise = page.render({
            canvasContext: context,
            viewport: viewport
        }).promise;
        await pdf2RenderPromise;
    } finally {
        isRendering2.value = false;
    }
}

// 缩放控制函数
async function zoomIn(pdfSide) {
    if (pdfSide === 1) {
        if (zoomLevels.value.left < maxZoom) {
            zoomLevels.value.left = Math.min(zoomLevels.value.left + zoomStep, maxZoom);
            await loadAndRenderPdf(page1.value, zoomLevels.value.left);
        }
    } else {
        if (zoomLevels.value.right < maxZoom) {
            zoomLevels.value.right = Math.min(zoomLevels.value.right + zoomStep, maxZoom);
            await loadAndRenderPdf2(page2.value, zoomLevels.value.right);
        }
    }
}

async function zoomOut(pdfSide) {
    if (pdfSide === 1) {
        if (zoomLevels.value.left > minZoom) {
            zoomLevels.value.left = Math.max(zoomLevels.value.left - zoomStep, minZoom);
            await loadAndRenderPdf(page1.value, zoomLevels.value.left);
        }
    } else {
        if (zoomLevels.value.right > minZoom) {
            zoomLevels.value.right = Math.max(zoomLevels.value.right - zoomStep, minZoom);
            await loadAndRenderPdf2(page2.value, zoomLevels.value.right);
        }
    }
}

async function resetZoom(pdfSide) {
    if (pdfSide === 1) {
        zoomLevels.value.left = defaultZoom;
        await loadAndRenderPdf(page1.value, zoomLevels.value.left);
    } else {
        zoomLevels.value.right = defaultZoom;
        await loadAndRenderPdf2(page2.value, zoomLevels.value.right);
    }
}

// 自动计算最佳缩放比例并居中显示差异
async function autoZoomAndCenter(diff) {
    if (!diff || !diff.details) return;
    
    const leftRect = diff.details.rectangleDoc1;
    const rightRect = diff.details.rectangleDoc2;
    
    const leftContainer = leftPdfViewer.value;
    const rightContainer = rightPdfViewer.value;
    
    // 记录哪些边有数据
    const hasLeftData = Boolean(leftRect);
    const hasRightData = Boolean(rightRect);
    
    // 处理左侧PDF定位和缩放（如果有数据）
    if (leftContainer && hasLeftData) {
        const containerWidth = leftContainer.clientWidth;
        const containerHeight = leftContainer.clientHeight;
        
        // 直接使用pixel坐标，避免重复转换
        const pageHeight = leftRect.pixelPageHeight || 722.835;
        const canvasX = leftRect.pixelX;
        const canvasY = leftRect.pixelY;
        const canvasWidth = leftRect.pixelWidth;
        const canvasHeight = leftRect.pixelHeight;
        
        // 计算合适的缩放比例
        const targetWidthScale = containerWidth * 0.7 / canvasWidth;
        const targetHeightScale = containerHeight * 0.7 / canvasHeight;
        const newZoom = Math.max(minZoom, Math.min(maxZoom, Math.min(targetWidthScale, targetHeightScale)));
        
        zoomLevels.value.left = newZoom;
        await loadAndRenderPdf(page1.value, newZoom);
        
        // 计算滚动位置，使差异区域居中
        const centerX = canvasX + canvasWidth / 2;
        const centerY = canvasY + canvasHeight / 2;
        
        const scrollLeft = Math.max(0, centerX * newZoom - containerWidth / 2);
        const scrollTop = Math.max(0, centerY * newZoom - containerHeight / 2);
        
        leftContainer.scrollLeft = scrollLeft;
        leftContainer.scrollTop = scrollTop;
        
        console.log('左侧差异定位详情:', {
            坐标: { x: canvasX, y: canvasY, width: canvasWidth, height: canvasHeight },
            缩放: newZoom,
            滚动位置: { left: scrollLeft, top: scrollTop },
            容器尺寸: { width: containerWidth, height: containerHeight }
        });
    }
    
    // 处理右侧PDF定位和缩放（如果有数据）
    if (rightContainer && hasRightData) {
        const containerWidth = rightContainer.clientWidth;
        const containerHeight = rightContainer.clientHeight;
        
        // 直接使用pixel坐标，避免重复转换
        const pageHeight = rightRect.pixelPageHeight || 722.835;
        const canvasX = rightRect.pixelX;
        const canvasY = rightRect.pixelY;
        const canvasWidth = rightRect.pixelWidth;
        const canvasHeight = rightRect.pixelHeight;
        
        // 计算合适的缩放比例
        const targetWidthScale = containerWidth * 0.7 / canvasWidth;
        const targetHeightScale = containerHeight * 0.7 / canvasHeight;
        const newZoom = Math.max(minZoom, Math.min(maxZoom, Math.min(targetWidthScale, targetHeightScale)));
        
        zoomLevels.value.right = newZoom;
        await loadAndRenderPdf2(page2.value, newZoom);
        
        // 计算滚动位置，使差异区域居中
        const centerX = canvasX + canvasWidth / 2;
        const centerY = canvasY + canvasHeight / 2;
        
        const scrollLeft = Math.max(0, centerX * newZoom - containerWidth / 2);
        const scrollTop = Math.max(0, centerY * newZoom - containerHeight / 2);
        
        rightContainer.scrollLeft = scrollLeft;
        rightContainer.scrollTop = scrollTop;
        
        console.log('右侧差异定位详情:', {
            坐标: { x: canvasX, y: canvasY, width: canvasWidth, height: canvasHeight },
            缩放: newZoom,
            滚动位置: { left: scrollLeft, top: scrollTop },
            容器尺寸: { width: containerWidth, height: containerHeight }
        });
    }
    
    // 调试信息
    console.log('差异定位完成:', {
        左侧有数据: hasLeftData,
        右侧有数据: hasRightData,
        左侧缩放: zoomLevels.value.left,
        右侧缩放: zoomLevels.value.right,
        差异类型: diff.type
    });
}

// 翻页按钮事件
async function prevPage(type) {
    if (isRendering1.value || isRendering2.value) return;
    
    clearDiffLine(); // 翻页前清除连线
    currentDiffIdx = null; // 清除当前差异索引
    
    if (type == 1) {
        if (page1.value > 1) {
            page1.value--
            await loadAndRenderPdf(page1.value)
        }
    } else {
        if (page2.value > 1) {
            page2.value--
            await loadAndRenderPdf2(page2.value)
        }
    }
}

async function nextPage(type) {
    if (isRendering1.value || isRendering2.value) return;
    
    clearDiffLine(); // 翻页前清除连线
    currentDiffIdx = null; // 清除当前差异索引
    
    if (type == 1) {
        if (page1.value < pdf1TotalPages.value) {
            page1.value++
            await loadAndRenderPdf(page1.value)
        }
    } else {
        if (page2.value < pdf2TotalPages.value) {
            page2.value++
            await loadAndRenderPdf2(page2.value)
        }
    }
}




function goBack() {
    // clearDiffLine(); // 离开页面前清除连线
    router.push('/home')
}

// 清除差异连线
function clearDiffLine() {
    const lineCanvas = document.getElementById('diff-line-canvas');
    if (lineCanvas) {
        lineCanvas.getContext('2d').clearRect(0, 0, lineCanvas.width, lineCanvas.height);
    }
}


let currentDiffIdx = null;
async function highlightDiff(idx) {
    if (isRendering1.value || isRendering2.value || idx === null || idx === undefined || !diffList.value[idx]) {
        console.warn('无效或重复索引:', idx);
        return;
    }

    currentDiffIdx = idx;
    const diff = diffList.value[idx];

    // 1. 获取页码信息
    const leftPage = diff.pageNumberDoc1 && diff.pageNumberDoc1 > 0 ? diff.pageNumberDoc1 : 1;
    const rightPage = diff.pageNumberDoc2 && diff.pageNumberDoc2 > 0 ? diff.pageNumberDoc2 : 1;

    // 2. 只在需要时翻页和渲染
    const needLeftRender = page1.value !== leftPage;
    const needRightRender = page2.value !== rightPage;

    if (needLeftRender) page1.value = leftPage;
    if (needRightRender) page2.value = rightPage;

    // 3. 并行渲染（仅在需要时）
    await Promise.all([
        needLeftRender ? loadAndRenderPdf(leftPage) : Promise.resolve(),
        needRightRender ? loadAndRenderPdf2(rightPage) : Promise.resolve()
    ]);

    // 4. 自动缩放、居中并绘制连线
    await autoZoomAndCenter(diff);
    drawDiffLine(diff);
}

/**
 * 根据传入的差异数据绘制连线，只在左右两边都有差异点时进行连线
 * @param {Object} diff 差异点数据，包含rectangleDoc1和rectangleDoc2
 */
function drawDiffLine(diff) {
    // 暂时禁用连线功能
    console.log('连线功能已禁用');
    return;
    
    /* 以下是连线功能的代码，暂时注释掉
    // 创建或获取画布
    let lineCanvas = document.getElementById('diff-line-canvas');
    if (!lineCanvas) {
        lineCanvas = document.createElement('canvas');
        lineCanvas.id = 'diff-line-canvas';
        lineCanvas.style.position = 'fixed';
        lineCanvas.style.left = '0';
        lineCanvas.style.top = '0';
        lineCanvas.style.pointerEvents = 'none';
        lineCanvas.style.zIndex = 9;
        document.body.appendChild(lineCanvas);
    }
    
    // 设置画布尺寸
    lineCanvas.width = window.innerWidth;
    lineCanvas.height = window.innerHeight;
    const ctx = lineCanvas.getContext('2d');
    ctx.clearRect(0, 0, lineCanvas.width, lineCanvas.height);
    
    // 检查左右两边是否都有差异数据
    const hasLeftData = diff.details && diff.details.rectangleDoc1 && diff.details.rectangleDoc1.x != null;
    const hasRightData = diff.details && diff.details.rectangleDoc2 && diff.details.rectangleDoc2.x != null;
    
    // 如果只有单边有数据，不绘制连线
    if (!hasLeftData || !hasRightData) {
        console.log('单边差异，不绘制连线:', {
            hasLeftData,
            hasRightData,
            diffType: diff.type
        });
        return;
    }
    
    // 准备高亮区域数据 - 使用与autoZoomAndCenter相同的pixel坐标
    const leftHighlight = hasLeftData ? {
        x: diff.details.rectangleDoc1.pixelX || diff.details.rectangleDoc1.x,
        y: diff.details.rectangleDoc1.pixelY || diff.details.rectangleDoc1.y,
        width: diff.details.rectangleDoc1.pixelWidth || diff.details.rectangleDoc1.width,
        height: diff.details.rectangleDoc1.pixelHeight || diff.details.rectangleDoc1.height,
        scale: 1, // pixel坐标已经是缩放后的
        viewportHeight: diff.details.rectangleDoc1.pixelPageHeight || diff.details.rectangleDoc1.pageHeight || 0
    } : null;
    
    const rightHighlight = hasRightData ? {
        x: diff.details.rectangleDoc2.pixelX || diff.details.rectangleDoc2.x,
        y: diff.details.rectangleDoc2.pixelY || diff.details.rectangleDoc2.y,
        width: diff.details.rectangleDoc2.pixelWidth || diff.details.rectangleDoc2.width,
        height: diff.details.rectangleDoc2.pixelHeight || diff.details.rectangleDoc2.height,
        scale: 1, // pixel坐标已经是缩放后的
        viewportHeight: diff.details.rectangleDoc2.pixelPageHeight || diff.details.rectangleDoc2.pageHeight || 0
    } : null;
    
    // 获取左右PDF画布位置
    const leftCanvas = pdfCanvas.value;
    const rightCanvas = pdfCanvas2.value;
    const leftRect = leftCanvas?.getBoundingClientRect();
    const rightRect = rightCanvas?.getBoundingClientRect();
    
    // 计算连接点
    const leftPoint = leftHighlight ? convertPdfToScreenCoords(leftHighlight, leftRect, 'left') : null;
    const rightPoint = rightHighlight ? convertPdfToScreenCoords(rightHighlight, rightRect, 'right') : null;
    
    // 只有当两边都有有效连接点时才绘制连线
    if (leftPoint && rightPoint) {
        // 绘制连线
        ctx.beginPath();
        ctx.strokeStyle = 'rgba(64, 158, 255, 0.8)';
        ctx.lineWidth = 2;
        ctx.shadowColor = 'rgba(64, 158, 255, 0.4)';
        ctx.shadowBlur = 6;
        
        // 绘制贝塞尔曲线
        ctx.beginPath();
        ctx.moveTo(leftPoint.x, leftPoint.y);
        
        // 调整贝塞尔曲线控制点
        const horizontalDistance = rightPoint.x - leftPoint.x;
        const controlDistance = Math.min(horizontalDistance * 0.3, 100); // 限制最大偏移
        
        ctx.bezierCurveTo(
            leftPoint.x + controlDistance,
            leftPoint.y,
            rightPoint.x - controlDistance,
            rightPoint.y,
            rightPoint.x,
            rightPoint.y
        );
        ctx.stroke();
        
        console.log('连线绘制完成:', {
            leftPoint,
            rightPoint,
            diffType: diff.type
        });
    }
    */ // 连线功能代码结束
}

function convertPdfToScreenCoords(pixelCoords, canvasRect, side = 'left') {
    if (!pixelCoords || !canvasRect) return null;
    
    // 获取PDF容器的滚动位置
    const pdfViewer = side === 'left' ? 
        document.querySelector('.pdf-viewer:first-child') : 
        document.querySelector('.pdf-viewer:last-child');
    const scrollTop = pdfViewer?.scrollTop || 0;
    const scrollLeft = pdfViewer?.scrollLeft || 0;
    
    // 直接使用pixel坐标（已经考虑了缩放和DPR）
    const screenX = canvasRect.left + pixelCoords.x - scrollLeft;
    const screenY = canvasRect.top + pixelCoords.y - scrollTop;
    
    let connectionPoint = {
        x: screenX,
        y: screenY + (pixelCoords.height / 2) // 取文本高度中点
    };
    
    // 根据左右位置调整连接点
    if (side === 'left') {
        connectionPoint.x = screenX + pixelCoords.width + connectionOffset.value.left;
    } else {
        connectionPoint.x = screenX + connectionOffset.value.right;
    }
    
    return connectionPoint;
}

onMounted(async () => {
    loading = ElLoading.service({
        lock: true,
        text: '加载中，请稍后',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    let result = JSON.parse(localStorage.getItem('res'));
    pdf1Url.value = result.generatedFiles[0];
    pdf2Url.value = result.generatedFiles[1];

    diffList.value = result.differences; // 从结果中获取差异列表

    similarity.value = 100 - result.totalDifferences || 0; // 获取相似度

    // pdf1Name.value = result.nameInfo.name1 || '比对文档1';
    // pdf2Name.value = result.nameInfo.name2 || '比对文档2';

    const loadingTask = pdfjsLib.getDocument(pdf1Url.value)
    pdf1Instance = await loadingTask.promise
    pdf1TotalPages.value = pdf1Instance.numPages
    await loadAndRenderPdf(page1.value)
    // 右侧PDF
    const loadingTask2 = pdfjsLib.getDocument(pdf2Url.value)
    pdf2Instance = await loadingTask2.promise
    pdf2TotalPages.value = pdf2Instance.numPages
    await loadAndRenderPdf2(page2.value)
    console.log('加载完成');
    loading.close()
    // 监听差异列表显示状态变化，调整缩放
    watch(showDiffList, (newVal) => {
        if (newVal) {
            // 差异列表显示时，缩小到175%
            zoomLevels.value.left = 1.75;
            zoomLevels.value.right = 1.75;
        } else {
            // 差异列表隐藏时，恢复到200%
            zoomLevels.value.left = 2.0;
            zoomLevels.value.right = 2.0;
        }
        // 重新渲染PDF
        loadAndRenderPdf(page1.value, zoomLevels.value.left);
        loadAndRenderPdf2(page2.value, zoomLevels.value.right);
    });
});

onBeforeUnmount(() => {
    console.log(loading);
    loading.close()
})

// 添加防抖函数
function debounce(fn, delay) {
    let timer = null;
    return function () {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(context, args);
        }, delay);
    };
}

// 在组件卸载时移除事件监听和清理画布
let scrollListeners = [];

onBeforeUnmount(() => {
    // 连线功能已禁用，暂时不移除画布
    /*
    // 清理滚动事件监听
    const pdfViewers = document.querySelectorAll('.pdf-viewer');
    pdfViewers.forEach((viewer, index) => {
        if (scrollListeners[index]) {
            viewer.removeEventListener('scroll', scrollListeners[index]);
        }
    });
    scrollListeners = [];
    
    // 移除画布
    const lineCanvas = document.getElementById('diff-line-canvas');
    if (lineCanvas) {
        lineCanvas.remove();
    }
    */
});
</script>

<style scoped>
.page-arrow-btn {
    width: 28px;
    height: 28px;
    border: 1px solid #409eff;
    color: #409eff;
    z-index: 20; /* 确保按钮在最上层 */
    position: relative;
}

.page-control-btns {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 25; /* 提高层级确保不被PDF遮盖 */
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    pointer-events: auto; /* 确保按钮可点击 */
}

.compare-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.compare-header {
    min-height: 57px;
    height: 57px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 32px;
    background: #1B1E25;
    color: #fff;
}

.connection-controls {
    display: flex;
    align-items: center;
    margin: 0 10px;
}

.connection-control-title {
    font-size: 14px;
    margin-right: 8px;
    white-space: nowrap;
}

.connection-control-buttons {
    display: flex;
    gap: 5px;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 16px;
}

.similarity b {
    color: #409eff;
    font-size: 14px;
}

/* 主体区域：PDF+差异列表 */
.compare-main {
    display: flex;
    flex-direction: row;
    background: #131218;
    overflow: hidden;
}

/* PDF内容区 */
.pdf-compare-content {
    flex: 1;
    display: flex;
    gap: 16px;
    padding: 16px 32px;
    transition: width 0.2s;
    min-width: 700px;
    position: relative; /* 确保翻页按钮定位正确 */
    z-index: 1;
}

.pdf-viewer {
    position: relative;
    flex: 1;
    min-width: 320px;
    background: #fff;
    border: 1.5px solid #2d2f37;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow-y: auto;
    overflow-x: hidden;
    z-index: 2; /* 降低PDF层级，让翻页按钮在上 */
}

/* 自定义滚动条样式 */
.pdf-viewer::-webkit-scrollbar {
    width: 6px;
}

.pdf-viewer::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.pdf-viewer::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
}

.pdf-viewer::-webkit-scrollbar-thumb:hover {
    background: #555;
}

/* 差异列表样式 */
.diff-list-panel {
    width: 20%;
    min-width: 260px;
    max-width: 400px;
    background: #23242a;
    color: #fff;
    padding: 24px 16px 0 16px;
    box-sizing: border-box;
    overflow-y: auto;
    border-left: 1px solid #222;
    display: flex;
    flex-direction: column;
}

.diff-list-title {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #fff;
}

.diff-item {
    background: #2d2f37;
    border-radius: 8px;
    padding: 16px 12px;
    margin-bottom: 18px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    cursor: pointer;
}

.diff-item:hover {
    border: 1.5px solid #409EFF;
}

.diff-title {
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 8px;
    color: #fff;
}

.diff-row {
    margin-bottom: 4px;
    font-size: 12px;
    word-break: break-all;
}

.diff-label {
    color: #aaa;
    margin-right: 4px;
}

.compare-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #1B1E25;
    border-top: 1px solid #1B1E25;
    height: 56px;
    padding: 0 32px;
    position: relative;
}

.footer-block {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 24px;
}

.footer-filename {
    color: #fff;
    font-weight: bold;
    font-size: 16px;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.footer-page {
    display: inline-flex;
    align-items: center;
    background: #23242a;
    border: 1.5px solid #444;
    padding: 2px 12px;
    font-size: 14px;
    font-weight: bold;
    min-width: 48px;
    justify-content: center;
    z-index: 2;
}

.page-current {
    color: #fff;
}

.page-sep,
.page-total {
    color: #aaa;
}

.similarity-badge {
    background: #2D2F37;
    padding: 2px 10px;
    border-radius: 4px;
    margin: 0 4px;
    display: inline-block;
}

.debug-active {
    background: #67c23a !important;
    border-color: #67c23a !important;
    color: #fff !important;
}

.pdf-canvas-full {
    width: 100%;
    height: 100%;
}

.footer-page-center {
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
}

:deep .el-overlay {
    background-color: transparent;
}

/* 新增样式 */
.pdf-container {
    display: flex;
    flex-direction: column;
    position: relative;
    flex: 1;
    min-width: 320px;
}

.control-panel {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding: 8px 12px;
    background: #2c3e50;
    border-bottom: 1px solid #34495e;
    border-radius: 8px 8px 0 0;
    gap: 10px;
}

.zoom-controls {
    display: flex;
    align-items: center;
    gap: 10px;
}

.zoom-level {
    font-size: 12px;
    color: #ecf0f1;
    min-width: 40px;
    text-align: center;
    font-weight: 500;
}

.page-controls {
    display: flex;
    align-items: center;
    gap: 8px;
}

.page-display {
    font-size: 12px;
    color: #ecf0f1;
    font-weight: 500;
    min-width: 50px;
    text-align: center;
}

.page-arrow-btn {
    background: rgba(255, 255, 255, 0.9);
    border: 1px solid #ddd;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.page-arrow-btn:hover {
    background: rgba(255, 255, 255, 1);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(-1px);
}

.page-arrow-btn:active {
    transform: translateY(0);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.pdf-viewer {
    position: relative;
    flex: 1;
    background: #fff;
    border: 1.5px solid #2d2f37;
    border-radius: 0 0 8px 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow-y: auto;
    overflow-x: hidden;
    margin-top: 0;
}

.zoom-controls .el-button-group {
    display: flex;
    gap: 2px;
}

.zoom-controls .el-button {
    padding: 4px 8px;
    font-size: 12px;
}

/* 差异列表侧边栏样式 - 深色主题 */
.diff-list-sidebar {
    width: 340px;
    background: #1B1E25;
    border-left: 1px solid #2d2f37;
    box-shadow: -2px 0 8px rgba(0, 0, 0, 0.3);
    display: flex;
    flex-direction: column;
    height: 100%;
}

.diff-list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #2d2f37;
    background: #23242a;
}

.diff-list-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #fff;
}

.diff-list-content {
    flex: 1;
    overflow-y: auto;
    padding: 10px 0;
    background: #1B1E25;
}

.diff-item {
    background: #2d2f37;
    border-radius: 8px;
    padding: 16px 12px;
    margin: 0 12px 12px 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    cursor: pointer;
    transition: all 0.3s ease;
}

.diff-item:hover {
    border: 1.5px solid #409EFF;
    transform: translateY(-1px);
}

.diff-title {
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 8px;
    color: #fff;
}

.diff-row {
    margin-bottom: 4px;
    font-size: 12px;
    word-break: break-all;
    color: #fff;
}

.diff-label {
    color: #aaa;
    margin-right: 4px;
}

.text-red-500 {
    color: #ff6b6b !important;
}

.text-white {
    color: #fff !important;
}

/* 调整主布局以容纳差异列表 */
.compare-main {
    flex: 1;
    display: flex;
    overflow: hidden;
}

.pdf-compare-content {
    display: flex;
    width: 100%;
    height: 100%;
    gap: 20px;
    transition: all 0.3s ease;
}

.compare-main.with-diff-list .pdf-compare-content {
    gap: 0;
}

.pdf-container {
    flex: 1;
    min-width: 0;
    transition: all 0.3s ease;
}

.compare-main.with-diff-list .pdf-container {
    flex: 1;
    min-width: 0;
}
</style>
